const http = require('http');
const fs = require('fs');

http
  .createServer(function (req, res) {
    getTitles(res);
  })
  .listen(3000, '127.0.0.1');

function getTitles(res) {
  fs.readFile('./chapter03/posts/titles.json', function (err, data) {
    if (err) {
      hasError(err, res);
    } else {
      getTemplate(JSON.parse(data.toString()), res);
    }
  });
}

function getTemplate(titles, res) {
  fs.readFile('./chapter03/posts/template.html', function (err, data) {
    if (err) {
      hasError(err, res);
    } else {
      formatHtml(titles, data.toString(), res);
    }
  });
}

function formatHtml(titles, tmpl, res) {
  const html = tmpl.replace('%', titles.join('</li><li>'));
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end(html);
}

function hasError(err, res) {
  console.log(err);
  res.end('Server Error');
}
